<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" href="${pageContext.request.contextPath }/bootstrap/img/favicon.ico">
<link href="${pageContext.request.contextPath }/bootstrap/css/style.min.css?v=4.0.0" rel="stylesheet">
<link href="${pageContext.request.contextPath }/bootstrap/css/animate.min.css" rel="stylesheet">
<link href="${pageContext.request.contextPath }/bootstrap/css/bootstrap.min.css?v=3.3.5" rel="stylesheet">
<link href="${pageContext.request.contextPath}/bootstrap/css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
<link href="${pageContext.request.contextPath }/bootstrap/css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/bootstrap/css/jquery-confirm.css"/>
<link href="${pageContext.request.contextPath }/bootstrap/css/plugins/jsTree/style.min.css" rel="stylesheet">
<title>角色管理</title>
</head>
<body>

	<div id="toolbar" class="btn-group pull-right" style="margin-right: 20px;">
		<button id="btn_edit" type="button" class="btn btn-default" style="display: none;" border-radius: 0">
			<span class="glyphicon glyphicon-pencil" aria-hidden="true" ></span>修改
		</button>
		<button id="btn_delete" type="button" class="btn btn-default" style="display: none;">
			<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
		</button>
		<button id="btn_add_role" type="button" class="btn btn-default">
			<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增角色
		</button>
		<button id="btn_add_rolemenu" type="button" class="btn btn-default">
			<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增角色权限
		</button>
	</div>
	
	<!-- 动态加载table -->
	<table id="Rolestab" class="table table-hover"></table>
	
	<div class="modal inmodal fade" id="RoleModal" tabindex="-1" role="dialog"  aria-hidden="true">
    	<div class="modal-dialog modal-lg">
        	<div class="modal-content">
            	<div class="modal-header">
                	<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title" id="role_modal_title"></h4>
               	</div>
                <div class="modal-body">
                	<input type="hidden" id="submittype"/>
                	<input type="hidden" id="roleid"/>
                	<div class="row">
                		<div class="col-sm-8">
                			<div class="form-group draggable">
		                    	<label class="control-label">角色名称：</label>
		                        <input type="text" name="rolename" id="rolename" onkeyup="words_deal_name();" class="form-control" placeholder="角色名称,字数1-10">
		                   	</div>
                		</div>
                	</div>
                	<div class="row">
                		<div class="col-sm-8">
                			<div class="form-group draggable">
		                    	<label class="control-label">角色描述：</label>
		                    	<textarea name="roledescription" id="roledescription" onkeyup="words_deal();" rows="4" class="form-control" placeholder="角色描述,字数1-80"></textarea>
		                   	</div>
                		</div>
                	</div>
                </div>
				<div class="modal-footer">
                	<button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                	<button type="button" class="btn btn-primary" onclick="RoleSubmit()" id="RoleBtn">提交</button>
           		</div>
           	</div>
        </div>
	</div>
	
	<div class="modal inmodal fade" id="DetailsModal" tabindex="-1" role="dialog"  aria-hidden="true">
    	<div class="modal-dialog modal-lg">
        	<div class="modal-content">
            	<div class="modal-header">
                	<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">角色详情</h4>
               	</div>
                <div class="modal-body">
                	<div class="row">
                		<div class="col-sm-12">
			                <div class="ibox float-e-margins">
			                    <div class="ibox-title">
			                        <h3>角色信息</h3>
			                    </div>
			                    <div class="ibox-content">
									<div class="row">
			                    		<div class="col-sm-6">
			                    			<p><i class="fa fa-user"> 角色名称：</i><strong><a id="Drolename"></a></strong></p>
			                    		</div>
			                    		<div class="col-sm-6">
			                    			<p><i class="fa fa-info"> 角色描述：</i><strong><a id="Droledescription"></a></strong></p>
			                    		</div>
			                    	</div>
			                    </div>
			                </div>
			            </div>
			            <div class="col-sm-12">
			                <div class="ibox float-e-margins">
			                    <div class="ibox-title">
			                        <h3>角色树形菜单</h3>
			                    </div>
			                    <div class="ibox-content">
			
			                        <div id="role_tree"></div>
			
			                    </div>
			                </div>
			            </div>
			        </div>
                </div>
				<div class="modal-footer">
                	<button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
           		</div>
           	</div>
        </div>
	</div>
	
	<div class="modal inmodal fade" id="RoleMenuModal" tabindex="-1" role="dialog"  aria-hidden="true">
    	<div class="modal-dialog modal-lg">
        	<div class="modal-content">
            	<div class="modal-header">
                	<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">新增角色权限</h4>
               	</div>
                <div class="modal-body">
                	<div class="row">
                		<div class="col-sm-8">
                			<div class="form-group draggable">
		                    	<label class="control-label">角色选择：（菜单选择中，不选择一级菜单的二级菜单不会在初始化中出现）</label>
		                    	<select class="form-control" name="adminrole" id="adminrole">
									<option value="0">---请选择---</option>
								</select>
		                   	</div>
                		</div>
                		<div class="col-sm-8">
                			<div class="form-group draggable">
		                    	<label class="control-label">角色选择：</label>
		                    	<select class="form-control" name="adminmenutitle" id="adminmenutitle" onchange="menutitlechange(this.value);">
									<option value="1">一级菜单</option>
									<option value="2">二级菜单</option>
								</select>
		                   	</div>
                		</div>
                	</div>
                	<div class="row">
                		<div class="col-sm-4">
                			<div class="form-group draggable">
		                    	<label class="control-label">一级菜单选择：</label>
		                    	<select class="form-control" name="fadminmenu" id="fadminmenu" onchange="loadadminmenu(this.value);">
									<option value="0">---请选择---</option>
								</select>
		                   	</div>
                		</div>
                		<div class="col-sm-4" style="display: none;" id="SadminmenuDiv">
                			<div class="form-group draggable">
		                    	<label class="control-label">二级菜单选择：</label>
		                    	<select class="form-control" name="sadminmenu" id="sadminmenu">
									<option value="0">---请选择---</option>
								</select>
		                   	</div>
                		</div>
                	</div>
                </div>
				<div class="modal-footer">
                	<button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                	<button type="button" class="btn btn-primary" onclick="RoleMenuSubmit()" id="RoleMenuBtn">提交</button>
           		</div>
           	</div>
        </div>
	</div>
	<script src="${pageContext.request.contextPath }/bootstrap/js/jquery.min.js?v=2.1.4"></script>
    <script src="${pageContext.request.contextPath }/bootstrap/js/bootstrap.min.js"></script>
    <script src="${pageContext.request.contextPath }/bootstrap/js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="${pageContext.request.contextPath }/bootstrap/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
    <script src="${pageContext.request.contextPath }/bootstrap/js/jquery-confirm.js"></script>
    <script src="${pageContext.request.contextPath }/bootstrap/js/plugins/jsTree/jstree.min.js"></script>
    <script type="text/javascript">
    $(window).resize(function() {
        $('#Rolestab').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })
    //查询按钮事件
    $('#search_btn').click(function(){
        //$('#doctortab').bootstrapTable('refresh');
        $('#Rolestab').bootstrapTable('refresh',{url: '${pageContext.request.contextPath}/Main/DynamicMenu/rolesListAjax.action'});
    })
    //tableHeight函数
    function tableHeight(){
        //可以根据自己页面情况进行调整
        return $(window).height()-220;
    }
  	function refreshTab(){
  		$('#Rolestab').bootstrapTable('refresh');
  	}
	//生成用户数据
    $('#Rolestab').bootstrapTable({
        method: 'get',
        contentType: "application/x-www-form-urlencoded",//必须要有！！！！
        url:"${pageContext.request.contextPath}/Main/DynamicMenu/rolesListAjax.action",//要请求数据的文件路径
        height:tableHeight(),//高度调整
        striped: true, //是否显示行间隔色
        dataField: "rows",//bootstrap table 可以前端分页也可以后端分页，这里
        //我们使用的是后端分页，后端分页时需返回含有total：总记录数,这个键值好像是固定的  
        //rows： 记录集合 键值可以修改  dataField 自己定义成自己想要的就好
        pageNumber: 1, //初始化加载第一页，默认第一页
        pagination:true,//是否分页
        queryParamsType:'limit',//查询参数组织方式
        queryParams:function(params) {//自定义参数，这里的参数是传给后台的，我这是是分页用的    
            return {//这里的params是table提供的    
                offset : params.offset,//从数据库第几条记录开始    
                limit : params.limit
            //找多少条    
            };},//请求服务器时所传的参数
        sidePagination:'server',//指定服务器端分页
        pageSize:10,//单页记录数
        pageList:[1,5,10,30,50,100],//分页步进值
        showRefresh:true,//刷新按钮
        showColumns:true,
        clickToSelect: true,//是否启用点击选中行
        toolbarAlign:'right',//工具栏对齐方式
        buttonsAlign:'right',//按钮对齐方式
        toolbar:'#toolbar',//指定工作栏
        columns:[
            {
                title:'全选',
                field:'select',
                //复选框
                checkbox:true,
                width:25,
                align:'center',
                valign:'middle'
            },
            {
                title:'角色ID',
                field:'roleid'
            },
            {
                title:'角色姓名',
                field:'rolename'
            },
            {
                title:'角色菜单ID',
                field:'rolemenuid'
            },
            {
                title:'角色描述',
                field:'roledescription'
            },
            {
                title:'操作',
                field:'operate',
              	//列数据格式化
                formatter:operate
            },
        ],
        locale:'zh-CN',//中文支持,
        responseHandler:function(rows){
            //在ajax获取到数据，渲染表格之前，修改数据源
            return rows;
        }
    })
    //操作序列规则化
	function operate(value,row,index){
		var roleid=row.roleid;
		var rolename="'"+row.rolename+"'";
		var roledescription="'"+row.roledescription+"'";
    	return '<button class="btn btn-primary" style="height:30px" onclick="Details('+roleid+','+rolename+','+roledescription+')">详情</button>&nbsp;&nbsp;<button class="btn btn-info" style="height:30px" onclick="editRole('+roleid+','+rolename+','+roledescription+')">编辑</button>&nbsp;&nbsp;<button class="btn btn-warning" style="height:30px" id="delete'+roleid+'" onclick="deleteRole('+roleid+')">删除</button>';
	}
	
	$("#btn_add_role").click(function(){
		$("#roleid").val("");
		$("#rolename").val("");
    	$("#roledescription").val("");
    	$("#submittype").val(1);
		$("#RoleModal").modal('show');
		$("#role_modal_title").html("新增角色");
	});
	
	$("#btn_add_rolemenu").click(function(){
		$("#RoleMenuModal").modal('show');
		var adminmenuid="fadminmenu";
		loadMenu(0,adminmenuid);
		loadrole();
	})
	/* 加载角色下拉框 */
	function loadrole(){
		$("#adminrole").empty();
		$('#adminrole').append("<option value='0' selected='selected' >" + '---请选择---' + "</option>");
		$.ajax({
			type:"post",
			url:"${pageContext.request.contextPath}/Main/DynamicMenu/getadminrole.action",
			async: true,
			//data:"menufatherid="+menufatherid,
    		success:function(data){
    			//alert("data.details.docname="+data.details.docname);
    			if(data.code==100){
    				var datalist = data.list;
                    for (var i = 0; i < datalist.length; i++) {  
                        $('#adminrole').append("<option value='" + datalist[i].roleid + "' >" + datalist[i].rolename + "</option>");  
                    }
    			}else{
    				$.alert(data.msg);
    			}
    		},error:function(){
    			$.alert("加载角色失败!!!");
    		}
		});
	}
	/* 一级菜单的onchange方法 */
	function loadadminmenu(menuid){
		var fadminmenu=$("#fadminmenu").val();
		var adminmenutitle=$("#adminmenutitle").val();
        if(fadminmenu==0){
        	$("#sadminmenu").empty();
            $('#sadminmenu').append("<option value='0' selected='selected' >" + '---请选择---' + "</option>");
        }else{
        	/* 这个是节省资源，二级选择一级菜单时候，二级菜单不加载 */
        	/* if(adminmenutitle==2){
        		var adminmenuid="sadminmenu";
        		loadMenu(menuid,adminmenuid);
        	} */
        	var adminmenuid="sadminmenu";
    		loadMenu(menuid,adminmenuid);
        }
	}
	function menutitlechange(value){
		if(value==1){
			$("#SadminmenuDiv").hide();
		}else if(value==2){
			$("#SadminmenuDiv").show();
		}
	}
	/* 加载菜单下拉框 */
	function loadMenu(menufatherid,adminmenuid){
		$("#"+adminmenuid).empty();
        $('#'+adminmenuid).append("<option value='0' selected='selected' >" + '---请选择---' + "</option>");
		$.ajax({
			type:"post",
			url:"${pageContext.request.contextPath}/Main/DynamicMenu/getadminmenu.action",
			async: true,
			data:"menufatherid="+menufatherid,
    		success:function(data){
    			//alert("data.details.docname="+data.details.docname);
    			if(data.code==100){
    				var datalist = data.list;
                    for (var i = 0; i < datalist.length; i++) {  
                        $('#'+adminmenuid).append("<option value='" + datalist[i].menuid + "' >" + datalist[i].menuname + "</option>");  
                    }
    			}else{
    				$.alert(data.msg);
    			}
    		},error:function(){
    			$.alert("加载菜单失败!!!");
    		}
		});
	}
	
	function RoleMenuSubmit(){
		var adminrole=$("#adminrole").val();
		var adminmenutitle = $("#adminmenutitle").val();
		/* if(adminmenutitle==1 && (adminrole==0 || fadminmenu==0)){
			$.alert("信息不可为空！");
			return false;
		}else if(adminmenutitle==2 && (adminrole==0 || fadminmenu==0 || sadminmenu)){
			$.alert("信息不可为空！");
			return false;
		} */
		var param="";
		if(adminmenutitle==1){
			var fadminmenu = $("#fadminmenu").val();
			param="roleid="+adminrole+"&menuid="+fadminmenu;
		}else if(adminmenutitle==2){
			var sadminmenu = $("#sadminmenu").val();
			param="roleid="+adminrole+"&menuid="+sadminmenu;
		}
		$("#RoleMenuBtn").html('<i class="fa fa-spinner fa-spin"></i>处理中...');
		$("#RoleMenuBtn").prop('disabled',true);
		$.ajax({
    		type:"post",
    		url:"${pageContext.request.contextPath}/Main/DynamicMenu/addadminrolemenu.action",
    		data:param,
    		async:true,
    		success:function(data){
    			$("#RoleMenuBtn").html('提交');
    			$("#RoleMenuBtn").prop('disabled',false);
    			$.alert(data.msg);
    			if(data.code=="100"){
	    			//refreshTab();
    				//$("#RoleMenuModal").modal('hide');
    			}
    		},error:function(request){
    			$("#RoleMenuBtn").html('提交');
    			$("#RoleMenuBtn").prop('disabled',false);
    			$.alert("服务器连接错误");
    		}
    	})
	}
	
	function  RoleSubmit(){
		var roleid = $("#roleid").val();
		var submittype = $("#submittype").val();
		
		var rolename = $("#rolename").val();
		var roledescription = $("#roledescription").val();
		var param;
    	var url;
		if(rolename=="" || roledescription==""){
			$.alert('信息不可为空！');
			return false;
		}
		if(submittype==1){
			param="rolename="+rolename+"&roledescription="+roledescription;
			url="${pageContext.request.contextPath}/Main/DynamicMenu/addadminrole.action";
		}else if(submittype==2){
			param="roleid="+roleid+"&rolename="+rolename+"&roledescription="+roledescription;
			url="${pageContext.request.contextPath}/Main/DynamicMenu/updateadminrole.action";
		}
		$("#RoleBtn").html('<i class="fa fa-spinner fa-spin"></i>处理中...');
		$("#RoleBtn").prop('disabled',true);
		ADDorEDIT(url,param);
	}
	
	function ADDorEDIT(url,param){
    	$.ajax({
    		type:"post",
    		url:url,
    		data:param,
    		async:true,
    		success:function(data){
    			$("#RoleBtn").html('提交');
    			$("#RoleBtn").prop('disabled',false);
    			$.alert(data.msg);
    			if(data.code=="100"){
	    			refreshTab();
    				$("#RoleModal").modal('hide');
    			}
    		},error:function(request){
    			$("#RoleBtn").html('提交');
    			$("#RoleBtn").prop('disabled',false);
    			$.alert("服务器连接错误");
    		}
    	})
    }
	
	function editRole(roleid,rolename,roledescription){
		$("#role_modal_title").html("编辑角色");
		$("#roleid").val(roleid);
		$("#rolename").val(rolename);
		$("#roledescription").val(roledescription);
		$("#submittype").val(2);
		$("#RoleModal").modal('show');
	}
	
	function deleteRole(roleid){
		$.confirm({
    		title:'提示！',
    		content:'您确定删除？',
    		type:'blue',
    		typeAnimated:true,
    		buttons:{
    			确定:function(){
    				$("#delete"+roleid).html('<i class="fa fa-spinner fa-spin"></i>处理中...');
    				$("#delete"+roleid).prop('disabled',true);
    				$.ajax({
    					type:'post',
    					url:"${pageContext.request.contextPath}/Main/DynamicMenu/deleterole.action",
    					data:"roleid="+roleid,
    					async:true,
    					success:function(data){
    						$("#delete"+roleid).html('删除');
    	    				$("#delete"+roleid).prop('disabled',false);
    	    				$.alert(data.msg);
    	    				if(data.code=="100"){
    	    					refreshTab();
    	    				}
    					},
    					error:function(request){
    						$("#delete"+roleid).html('删除');
    	    				$("#delete"+roleid).prop('disabled',false);
    	    				$.alert('服务器链接错误！');
    					}
    				});
    			},
    			取消:function(){},
    		}
    	});
	}
	
	function Details(roleid,rolename,roledescription){
		$("#DetailsModal").modal('show');
		$.jstree.destroy ("#role_tree");//重点，销毁原加载的jstree，重新加载新的jstree
		Initroletree(rolename);
		$("#Drolename").html(rolename);
		$("#Droledescription").html(roledescription);
	}
	
	function words_deal_name(){
    	var rolename=$('#rolename').val().length;
    	var value=$("#rolename").val();
    	$("#rolename").val(value.replace(/\s/g,''));
        if(rolename>10){
        	var num=$("#rolename").val().substr(0,10);
        	$("#rolename").val(num);
        	//alert("超过字数限制，多出的字将被截断！" );
        }
    }
    function words_deal(){
    	var roledescription=$('#roledescription').val().length;
    	var value=$("#roledescription").val();
    	$("#roledescription").val(value.replace(/\s/g,''));
        if(roledescription>80){
        	var num=$("#roledescription").val().substr(0,80);
        	$("#roledescription").val(num);
        	//alert("超过字数限制，多出的字将被截断！" );
        }
    }
    </script>
    <script>
        function Initroletree(rolename){
        	var nodes=[];//父节点
        	var tnodes=[];//总的节点
        	$.ajax({
    			type:"post",
    			url:"${pageContext.request.contextPath}/Main/DynamicMenu/getadminmenu.action",
    			async: true,
    			data:"menufatherid=-1",
        		success:function(data){
        			if(data.code==100){
        				var datalist = data.list;
        				for(var i=0;i<datalist.length;i++){
        					if(datalist[i].menufatherid!=0){
        						var node={menuid:datalist[i].menuid,menuname:datalist[i].menuname,menufatherid:datalist[i].menufatherid,menuurl:datalist[i].menuurl};
            	        		tnodes.push(node);
        					}
        	        	}
        				for(var i=0;i<datalist.length;i++){
        					var tnodeskey=[];//分段子节点
        					if(datalist[i].menufatherid==0){
        						var row = datalist[i];
        						for(var j=0;j<tnodes.length;j++){
        							if(tnodes[j].menufatherid==row.menuid){
        								var node={text:tnodes[j].menuname+"-"+tnodes[j].menuurl,icon:"none"};
        								tnodeskey.push(node);
        							}
        						}
        						var Fnode={text:row.menuname,icon:"fa fa-folder",state:{"opened":false},children:tnodeskey};
        						nodes.push(Fnode);
        					}
        				}
        				$("#role_tree").jstree({
        	        		"core":{"data":{"text":"<input type='checkbox' name='checkbox'/>"+rolename,"state":{"opened":true},"icon":"fa fa-folder",children:nodes}}
        	        	});
        			}else{
        				$.alert(data.msg);
        			}
        		},error:function(){
        			$.alert("加载总菜单失败!!!");
        		}
    		});
        	
        }
    </script>
</body>
</html>